package org.dromara.system.service.impl;

import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.excel.core.ExcelResult;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.system.domain.WbCompanyBlacklist;
import org.dromara.system.domain.dr.WbMinuteBidBagDR;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.WbProjectInfoBo;
import org.dromara.system.domain.vo.WbProjectInfoVo;
import org.dromara.system.domain.WbProjectInfo;
import org.dromara.system.mapper.WbProjectInfoMapper;
import org.dromara.system.service.IWbProjectInfoService;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 计划Service业务层处理
 *
 * @author Lion Li
 * @date 2024-04-22
 */
@RequiredArgsConstructor
@Service
public class WbProjectInfoServiceImpl implements IWbProjectInfoService {

    private final WbProjectInfoMapper baseMapper;

    /**
     * 查询计划
     */
    @Override
    public WbProjectInfoVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询计划列表
     */
    @Override
    public TableDataInfo<WbProjectInfoVo> queryPageList(WbProjectInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<WbProjectInfo> lqw = buildQueryWrapper(bo);
        Page<WbProjectInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询计划列表 (小程序)
     */
    @Override
    public TableDataInfo<WbProjectInfoVo> queryPageListZ(WbProjectInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<WbProjectInfo> lqw = buildQueryWrapper(bo);
        lqw.ne(WbProjectInfo::getStatus, "-1");
        lqw.orderByDesc(WbProjectInfo::getId);
        Page<WbProjectInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        for (WbProjectInfoVo vo : result.getRecords()) {
            if (vo.getEstimatePublishTime() != null && vo.getEstimatePublishTime().getTime() > System.currentTimeMillis()) {
                vo.setStatusName("未招标");
            }else{
                vo.setStatusName("已招标");
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询计划列表
     */
    @Override
    public List<WbProjectInfoVo> queryList(WbProjectInfoBo bo) {
        LambdaQueryWrapper<WbProjectInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<WbProjectInfo> buildQueryWrapper(WbProjectInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<WbProjectInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getItemId()), WbProjectInfo::getItemId, bo.getItemId());
        lqw.like(StringUtils.isNotBlank(bo.getItemName()), WbProjectInfo::getItemName, bo.getItemName());
        lqw.like(bo.getEstimatePublishTime() != null, WbProjectInfo::getEstimatePublishTime, bo.getEstimatePublishTime());
        lqw.like(StringUtils.isNotBlank(bo.getProvinceName()), WbProjectInfo::getProvinceName, bo.getProvinceName());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), WbProjectInfo::getStatus, bo.getStatus());
        lqw.apply(params.get("estimatePublishTime") != null,"date_format(estimate_publish_time, {0}) = {1}", "%Y-%m", params.get("estimatePublishTime"));
        lqw.orderByAsc(WbProjectInfo::getEstimatePublishTime);
        return lqw;
    }

    /**
     * 新增计划
     */
    @Override
    public Boolean insertByBo(WbProjectInfoBo bo) {
        WbProjectInfo add = MapstructUtils.convert(bo, WbProjectInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改计划
     */
    @Override
    public Boolean updateByBo(WbProjectInfoBo bo) {
        WbProjectInfo update = MapstructUtils.convert(bo, WbProjectInfo.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(WbProjectInfo entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除计划
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public R importDate(ExcelResult<WbProjectInfoVo> result) {
        int num = 0;
        int err=0;
        try {
            List<WbProjectInfoVo> list = result.getList();
            if (list.isEmpty()){
                return R.ok("导入空数据", num);
            }
            List<WbProjectInfoVo> wbProjectInfoVos = new ArrayList<>();
            for (WbProjectInfoVo wbProjectInfoVo : list) {
                err++;
                wbProjectInfoVos.add(wbProjectInfoVo);
                num++;
            }
            baseMapper.importDate(wbProjectInfoVos);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.fail("第"+err+"条数据出现错误，请联系管理员", e);
        }
        return R.ok("导入数据成功条数", num);
    }
}
